package com.ygxsk.carhome.ui.leads;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.enumwrap.LeadCarStepStatus;
import com.ygxsk.carhome.event.EventLeadMain;
import com.ygxsk.carhome.response.LeadListItemBean;
import com.ygxsk.carhome.response.LeadListItemBeanOutSide;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.LeadListItemAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.ClearEditTextNoClearSK;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.internal.DebouncingOnClickListener;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2024/2/20  12:06
 * @Description:潜客的历史记录列表，主要的是 成功的状态的  列表
 */
public class LeadHistoryActivity extends ErrorActivity {

    //搜索框逻辑
    @BindView(R.id.et_searchincustomsmall)
    ClearEditTextNoClearSK et_searchInCustomSmall;

    //搜索文字 按钮内容
    @BindView(R.id.textviewsearchincustomsmall)
    TextView textViewSearchInCustomSmall;

    @BindView(R.id.refreshlayoutinleadshistory)
    SmartRefreshLayout refreshLayoutInLeadsHistory;

    @BindView(R.id.recyclerviewinleadhistory)
    RecyclerView recyclerViewInLeadHistory;

    //历史记录适配器：
    private LeadListItemAdapter leadListItemAdapter;

    //最后一条上传的id的信息内容
    private int pagination_upLoad = Parameterkey.pageNum_default_first;

    //潜在客户，
    private ArrayList<LeadListItemBean> mDataResources = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        initloading();

        initViews();

        //默认是直接调用接口的
        gainDatas();


        //需要再次监听，例如：这个用户这次是成功，下次再来买车或者卖车 还是要跟进进度的。
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_lead_history;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.leadscustomer));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                KeyboardUtils.hideSoftInput(mActivityInstance);

                methodBack();

            }
        });

        toolbarHelper.setLayoutRight(false, 0, "", null);

        //添加潜在客户的按钮
//        toolbarHelper.setLayoutRight(true, 1, getString(R.string.title_right_addlead), new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //快速双加的限制，
//                Bundle extra_bundle = new Bundle();
//                //标志【添加】
//                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_LEAD_ADD);
//                ActivityUtils.startActivity(extra_bundle, LeadAddSubmitActivity.class);
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //填充默认的搜索框hint
        if (et_searchInCustomSmall != null) {
            et_searchInCustomSmall.setHint(getString(R.string.search_keyword_full_name));
            et_searchInCustomSmall.clearFocus();
        }

        //使用rxbinding做监听，如果1秒钟没有输入的话就自动清除焦点
//            RxTextView.afterTextChangeEvents(et_searchInCustom)
//                    .debounce(1000, TimeUnit.MILLISECONDS)//
//                    .skip(1)//过滤到第一个空字符的内容
//                    .subscribeOn(AndroidSchedulers.mainThread())//
//                    .observeOn(AndroidSchedulers.mainThread())//
//                    .subscribe(new Consumer<TextViewAfterTextChangeEvent>() {
//                        @Override
//                        public void accept(TextViewAfterTextChangeEvent textViewAfterTextChangeEvent) throws Throwable {
//
//                            //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "监听到的内容是->" + textViewAfterTextChangeEvent.getView().getText().toString());
////                            if (et_searchInCustom.isFocused()) {
////                                //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "afterTextChangeEvents--处于获取焦点状态");
////                                et_searchInCustom.clearFocus();//如果处于占用焦点之中，那么清理焦点
////                            }
//
//                            if (!TextUtils.isEmpty(textViewAfterTextChangeEvent.getView().getText().toString())){
//                                method_SearchSomeThing();
//                            }
//
//                        }
//                    }, new Consumer<Throwable>() {
//
//                        @Override
//                        public void accept(Throwable throwable) throws Throwable {
//                            //
//                        }
//                    });

        //软键盘的【搜索】
        et_searchInCustomSmall.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH || (keyEvent != null && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {

                    //关闭软键盘
                    KeyboardUtils.hideSoftInput(LeadHistoryActivity.this);

                    method_SearchSomeThing();

                    return true;
                }

                return false;
            }
        });

        if (textViewSearchInCustomSmall != null) {

            textViewSearchInCustomSmall.setOnClickListener(new DebouncingOnClickListener() {
                @Override
                public void doClick(View v) {

                    if (KeyboardUtils.isSoftInputVisible(LeadHistoryActivity.this)) {
                        KeyboardUtils.hideSoftInput(LeadHistoryActivity.this);
                    }

                    method_SearchSomeThing();

                }
            });
        }

        //布局的适配器填充，下拉刷新等等；
        recyclerViewInLeadHistory.setLayoutManager(new MyLinearLayoutManager(this));

        leadListItemAdapter = new LeadListItemAdapter(R.layout.leadlistfragmentadapter, mDataResources);
        recyclerViewInLeadHistory.setAdapter(leadListItemAdapter);

        leadListItemAdapter.notifyDataSetChanged();

        //2024年1月26日15:24:39 因为水波纹效果 所以去掉这个点击
        leadListItemAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                LeadListItemBean leadListItemBean = (LeadListItemBean) adapter.getItem(position);

                if (leadListItemBean != null) {
                    //携带这条数据，主要是携带id
                    Bundle extra_bundle = new Bundle();
                    extra_bundle.putParcelable(ExtraKey.EXTRA_LEAD_LIST_ITEM_BEAN, leadListItemBean);
                    ActivityUtils.startActivity(extra_bundle, LeadDetailActivity.class);
                }

            }
        });

        leadListItemAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                LeadListItemBean leadListItemBean = (LeadListItemBean) adapter.getItem(position);

                switch (view.getId()) {

//                    case R.id.materialripplelayoutoutsidelead: {//点击外侧的水波纹效果
//
//                        if (leadListItemBean != null) {
////                          //携带这条数据，主要是携带id
//                            Bundle extra_bundle = new Bundle();
//                            extra_bundle.putParcelable(ExtraKey.EXTRA_LEAD_LIST_ITEM_BEAN, leadListItemBean);
//                            ActivityUtils.startActivity(extra_bundle, LeadDetailActivity.class);
//                        }
//
//                        break;
//                    }

                    case R.id.textvieweditviewphone: {

                        clickButton_toCallPhone(LeadHistoryActivity.this, leadListItemBean.getCustomerPhone(), CallHistoryBusinessType.BUSINESSTYPE_1.getIndex());

                        break;
                    }

                    default:
                        break;
                }
            }
        });


        refreshLayoutInLeadsHistory.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        pagination_upLoad = Parameterkey.pageNum_default_first;

                        //类型选项重置
//                        latentType_upLoad = "";
                        //客户来源选项重置
//                        createsource_upLoad = "";
                        //跟进状态
//                        status_upLoad = "";

                        //重置3个筛选标题
//                        nice_spinner_carType.setText(StringUtils.getString(R.string.please_choose_cartype));
//                        nice_spinner_formWhere.setText(StringUtils.getString(R.string.please_choose_formwhere));
//                        nice_spinner_stateItem.setText(StringUtils.getString(R.string.please_choose_state_assigned));

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        if (leadListItemAdapter != null) {
                            leadListItemAdapter.notifyDataSetChanged();
                        }

                        getServerDatas();

                        refreshLayout.finishRefresh();
                    }
                });

            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        getServerDatas();

                        refreshLayout.finishLoadMore();

                    }
                });
            }
        });

    }

    @Override
    protected void gainDatas() {

        pagination_upLoad = Parameterkey.pageNum_default_first;//重置

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (leadListItemAdapter != null) {
            leadListItemAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {
            netWorkError();
            setEnableLoadmore(refreshLayoutInLeadsHistory, false);
        }


    }

    private void method_SearchSomeThing() {

        //获取搜索的关键字内容,刚开始默认是空值
        String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();

        if (!TextUtils.isEmpty(keyWord_upLoad) && (keyWord_upLoad).length() < Parameterkey.keyWordLength) {
            //ToastUtils.showShort("最少输入两个字符！");
            CommUtils.checkDialog(mAlertView);
            mAlertView = CommUtils.method_showAlertViewSingleSlowly(LeadHistoryActivity.this, ConstantSign.ALERT_TITLE, StringUtils.getString(R.string.pleaseinputkeywordtwo), true);
            mAlertView.show();
            return;
        }

        //如果发起搜索，要重置 第一页
        pagination_upLoad = Parameterkey.pageNum_default_first;

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (leadListItemAdapter != null) {
            leadListItemAdapter.notifyDataSetChanged();
        }

        getServerDatas();

        if (TextUtils.isEmpty(et_searchInCustomSmall.getText().toString().trim())) {
            ToastUtils.make().setGravity(Gravity.CENTER, 0, 0);
            ToastUtils.showShort(getString(R.string.pleaseinputkeyword));
        }

    }


    private void getServerDatas() {

        String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();

        HashMap<String, Object> map = new HashMap<>();

        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,

//        map.put(Parameterkey.latentType, latentType_upLoad);//,潜客类型 1新车;2二手车
//        map.put(Parameterkey.createsource, createsource_upLoad);//客户来源：0预约试驾；1预约看车；2自然到店；3以旧换新

        //只有【成功】状态://跟进状态：0:待联系;1:已分配;2:有意向;3无意向;4成功;5战败;6取消预约
        map.put(Parameterkey.status, LeadCarStepStatus.LEAD_STEP_SUCCESS.getIndex());


        map.put(Parameterkey.keyWord, keyWord_upLoad);//,搜索关键字
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.GETSHOPLATENTCUSTOMERLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getShopLatentCustomerList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getShopLatentCustomerList(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(LeadHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<LeadListItemBeanOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
                        if (refreshLayoutInLeadsHistory != null) {
                            refreshLayoutInLeadsHistory.setEnableLoadMore(true);
                        }
                    }
                }).subscribe(new Consumer<LeadListItemBeanOutSide>() {
                    @Override
                    public void accept(LeadListItemBeanOutSide leadListItemBeanOutSide) throws Throwable {

                        if (leadListItemBeanOutSide != null) {

                            ArrayList<LeadListItemBean> currentDatas = leadListItemBeanOutSide.getDataList();

                            if (currentDatas != null && !currentDatas.isEmpty()) {
                                if (mDataResources != null) {
                                    mDataResources.addAll(currentDatas);
                                }
                            }
                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDataResources != null && mDataResources.isEmpty()) {
                            //同时禁用加载更多；
                            if (refreshLayoutInLeadsHistory != null) {
                                refreshLayoutInLeadsHistory.setEnableLoadMore(false);
                            }

                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
                        }

                        if (leadListItemAdapter != null) {
                            leadListItemAdapter.notifyDataSetChanged();
                        }

                        //给分页值
                        pagination_upLoad = leadListItemBeanOutSide.getNextPagination();

                        //对列表改造：
                        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
                            setFinishLoadMoreWithNoMoreData(refreshLayoutInLeadsHistory, true);
                        } else {
                            setEnableLoadmore(refreshLayoutInLeadsHistory, true);
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        function_apiException(apiException);

                    }
                });

    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        switch (what_method) {

            case ConstantApi.GETSHOPLATENTCUSTOMERLIST_URL: {

                if (mDataResources != null && mDataResources.isEmpty()) {

                    if (refreshLayoutInLeadsHistory != null) {
                        refreshLayoutInLeadsHistory.setEnableLoadMore(false);
                    }

                    CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                            serverCode,//
                            R.drawable.errorsear,//
                            serverMessage,//
                            getString(R.string.nulldatanow));
                }

                break;
            }

            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInLeadHistory(EventLeadMain eventLeadMain) {

        if (eventLeadMain != null) {

            if (eventLeadMain.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_LEADMAINLIST) {

                //如果发起搜索，要重置 第1页
                pagination_upLoad = Parameterkey.pageNum_default_first;

                //清空历史数据
                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                if (leadListItemAdapter != null) {
                    leadListItemAdapter.notifyDataSetChanged();
                }

                getServerDatas();

            }

        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
            if (leadListItemAdapter != null) {
                leadListItemAdapter.notifyDataSetChanged();
            }
            leadListItemAdapter = null;
        }

        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void methodBack() {

        methodBackFinish();

    }
}